package com.heroCW.bodhiAttic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heroCW.bodhiAttic.common.BaseContext;
import com.heroCW.bodhiAttic.exception.CustomException;
import com.heroCW.bodhiAttic.dto.OrdersDto;
import com.heroCW.bodhiAttic.entity.*;
import com.heroCW.bodhiAttic.mapper.OrderMapper;
import com.heroCW.bodhiAttic.resultUtil.ResultCode;
import com.heroCW.bodhiAttic.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户支付
     *
     * @param orders
     */
    @Override
    @Transactional
    public Boolean submit(Orders orders) {
        Boolean[] flags = new Boolean[3];
        // 获取当前用户Id
        Long userId = BaseContext.getCurrentId();

        // 查询当前用户购物车
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);

        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new CustomException(ResultCode.CUSTOM_CANNOT_SAVE_ERR, "购物车为空，不能下单");
        }

        // 查询用户信息
        User user = userService.getById(userId);

        // 查询地址信息
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);

        if (addressBook == null) {
            throw new CustomException(ResultCode.CUSTOM_CANNOT_SAVE_ERR, "用户地址信息有误，不能下单");
        }

        Long orderId = IdWorker.getId();    //订单号

        AtomicInteger amount = new AtomicInteger(0);

        // 像订单明细表插入数据，多条数据
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        // 向订单表插入数据，1条数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        flags[0] = this.save(orders);

        flags[1] = orderDetailService.saveBatch(orderDetails);

        // 清空购物车数据
        flags[2] = shoppingCartService.remove(wrapper);

        for (Boolean flag : flags) {
            if (!flag)
                return false;
        }
        return true;
    }

    @Override
    public IPage<OrdersDto> getPage(int page, int pageSize, String number, String beginTime, String endTime) {

        IPage<Orders> pageInfo = new Page<>(page, pageSize);

        // orders数据表查询条件封装
        LambdaQueryWrapper<Orders> ordersWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(number)) {
            ordersWrapper.like(Orders::getId, number);
            ordersWrapper.or().like(Orders::getUserName, number);
        }

        ordersWrapper.ge(StringUtils.isNotEmpty(beginTime),Orders::getOrderTime, beginTime)
                .le(StringUtils.isNotEmpty(endTime),Orders::getOrderTime, endTime);
        ordersWrapper.orderByDesc(Orders::getOrderTime);

        this.page(pageInfo, ordersWrapper);

        return this.copyToOrdersDto(pageInfo, page, pageSize);
    }

    @Override
    public IPage<OrdersDto> getOrderPage(int page, int pageSize) {
        // h获取当前用户id
        Long userId = BaseContext.getCurrentId();

        IPage<Orders> pageInfo = new Page<>(page, pageSize);

        // 条件构造器
        LambdaQueryWrapper<Orders> orderWrapper = new LambdaQueryWrapper<>();
        orderWrapper.eq(userId != null, Orders::getUserId, userId);
        orderWrapper.orderByDesc(Orders::getOrderTime);

        this.page(pageInfo, orderWrapper);

        return this.copyToOrdersDto(pageInfo, page, pageSize);
    }

    @Override
    public IPage<OrdersDto> copyToOrdersDto(IPage<Orders> pageInfo, int page, int pageSize) {

        IPage<OrdersDto> ordersDtoPage = new Page<>(page, pageSize);

        List<OrdersDto> list = pageInfo.getRecords().stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            Long orderId = item.getId();

            LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
            orderDetailWrapper.eq(OrderDetail::getOrderId, orderId);

            List<OrderDetail> details = orderDetailService.list(orderDetailWrapper);

            BeanUtils.copyProperties(item, ordersDto);

            ordersDto.setOrderDetails(details);
            return ordersDto;

        }).collect(Collectors.toList());

        BeanUtils.copyProperties(pageInfo, ordersDtoPage, "records");
        ordersDtoPage.setRecords(list);

        return ordersDtoPage;
    }

    @Override
    @Transactional
    public Boolean updateOrder(Long orderId, Integer status) {
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Orders::getId, orderId);
        updateWrapper.set(Orders::getStatus, status);
        return this.update(updateWrapper);
    }

    @Override
    @Transactional
    public Boolean oneMoreOrder(Long orderId) {

        Long userId = BaseContext.getCurrentId();   //用户id

        LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
        orderDetailWrapper.eq(OrderDetail::getOrderId, orderId);
        List<OrderDetail> details = orderDetailService.list(orderDetailWrapper);
        List<ShoppingCart> shoppingCarts = details.stream().map((item) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(item, shoppingCart);

            ShoppingCart shoppingCart1 = shoppingCartService.getById(shoppingCart.getId());
            if (shoppingCart1 != null) {
                throw new CustomException(ResultCode.CUSTOM_CANNOT_SAVE_ERR, "该订单已在购物车里，不能重复下单");
            }

            shoppingCart.setUserId(userId);
            return shoppingCart;
        }).collect(Collectors.toList());


        return shoppingCartService.saveBatch(shoppingCarts);
    }
}
